<template>
  <div style="opacity: 0.88;">
    <div class="manage-form">
      <div class="manage-title">
        <h2>管理二手商品</h2>
      </div>
      <div class="search-container" style="margin-bottom: 20px;">
        <el-input v-model="searchName" placeholder="按名称搜索商品" style="width: 300px; margin-right: 20px;" />
        <el-button @click="searchProduct">搜索</el-button>
      </div>
      <el-table :data="paginatedData" style="width: 100%">
        <el-table-column label="No" prop="no" />
        <el-table-column label="Name" prop="name" />
        <el-table-column label="Image" prop="image">
          <template v-slot="{ row }">
            <img :src="`/${row.image}`" alt="Product Image" style="max-width: 100px; max-height: 100px;">
          </template>
        </el-table-column>
        <el-table-column label="Quantity" prop="quantity" />
        <el-table-column label="Price" prop="price" />
        <el-table-column label="Grounding" prop="ifground">
          <template v-slot="{ row }">
            <span>{{ row.ifground === 1 ? '已上架' : '未上架' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="Actions">
          <template v-slot="{ row }">
            <el-button @click="editProduct(row)">编辑</el-button>
            <el-button @click="deleteProduct(row.id)" type="danger">删除</el-button>
            <el-button @click="openAdditionalImageDialog(row)">附加图片编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-size="pageSize"
        :total="filteredData.length"
        layout="total, prev, pager, next, jumper"
      ></el-pagination>
    </div>

    <el-dialog v-model="dialogFormVisible" title="编辑商品" width="500" @close="cancelEdit">
      <el-form :model="editForm">
        <el-form-item label="名称">
          <el-input v-model="editForm.name"></el-input>
        </el-form-item>
        <el-form-item label="数量">
          <el-input v-model="editForm.quantity" type="number"></el-input>
        </el-form-item>
        <el-form-item label="价格">
          <el-input v-model="editForm.price" type="number"></el-input>
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="editForm.description"></el-input>
        </el-form-item>
        <el-form-item label="上架状态">
          <el-radio-group v-model="editForm.ifground">
            <el-radio :label="1">已上架</el-radio>
            <el-radio :label="0">未上架</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="图片">
          <input type="file" @change="handleFileChange" ref="fileInput">
          <img v-if="editForm.image" :src="`/${editForm.image}`" alt="Product Image" style="max-width: 100px; max-height: 100px;">
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelEdit">取消</el-button>
          <el-button type="primary" @click="updateProduct">保存</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog v-model="additionalImageDialogVisible" title="附加图片" width="500" @close="cancelAdditionalImageUpload">
      <el-form>
        <el-form-item label="添加文件成功即上传">
          <input type="file" @change="handleAdditionalFileChange" ref="additionalFileInput">
          <div v-if="additionalFilesPreview.length">
            <img v-for="(file, index) in additionalFilesPreview" :src="file" :key="index" style="max-width: 100px; max-height: 100px;">
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="deleteAdditionalImageUpload">删除历史附加图</el-button>
          <el-button @click="fetchProductImages">查看历史附加图</el-button>
          <el-button type="primary" @click="uploadAdditionalImages">上传</el-button>
        </div>
      </template>
    </el-dialog>
    
    <!-- 查看历史图片的弹窗 -->
    <el-dialog v-model="historyImageDialogVisible" title="历史图片" width="500">
      <div v-if="productImages.length">
        <img v-for="(image, index) in productImages" :src="image" :key="index" style="max-width: 100px; max-height: 100px; margin: 5px;">
      </div>
      <div v-else>
        没有历史图片
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="historyImageDialogVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { ref, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import axios from 'axios';
import { globalState } from '../global'; // 引用 globalState

const router = useRouter();

const tableData = ref([]);
const dialogFormVisible = ref(false);
const editForm = ref({ id: '', name: '', quantity: '', price: '', ifground: 0, description: '', image: '' });
const currentPage = ref(1);
const pageSize = ref(10);
const searchName = ref('');
const file = ref(null);
const additionalFiles = ref([]);
const additionalFilesPreview = ref([]);
const fileInput = ref(null); // 用于引用文件输入元素
const additionalFileInput = ref(null);
const additionalImageDialogVisible = ref(false); // 新增附加图片弹窗的可见性
const selectedProductId = ref(null); // 记录选中的产品 ID

const fetchData = async () => {
  try {
    const response = await axios.get('http://localhost:8080/api/products'); // 获取所有商品
    console.log(response.data);  // 输出返回的数据

    if (Array.isArray(response.data)) {
      tableData.value = response.data
        .filter(item => item.sellerUsername === globalState.username) // 过滤出当前用户的商品
        .map((item, index) => ({
          no: index + 1,
          id: item.id,
          name: item.name,
          image: item.image,
          quantity: item.quantity,
          price: item.price,
          ifground: item.ifground,
          description: item.description,
          sellerUsername: item.sellerUsername, // 保存商品的卖家用户名
        }));
    } else {
      console.error('Expected an array of products but received:', response.data);
    }
  } catch (error) {
    console.error('Error fetching data:', error);
  }
};
const historyImageDialogVisible = ref(false);
const productImages = ref([]); // 添加这行定义
const fetchProductImages = async () => {
  try {
    const response = await axios.get(`http://localhost:8080/api/images/${selectedProductId.value}`);
    productImages.value = response.data;
    historyImageDialogVisible.value = true;
    console.log('历史图片获取成功:', response.data);
  } catch (error) {
    console.error('获取历史图片失败:', error);
  }
};

const searchProduct = () => {
  currentPage.value = 1;  // 重置分页到第一页
};

const filteredData = computed(() => {
  return tableData.value.filter(item => {
    return item.sellerUsername === globalState.username && // 过滤当前用户的商品
           item.name.toLowerCase().includes(searchName.value.toLowerCase());
  });
});

const paginatedData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return filteredData.value.slice(start, end);
});

const handleCurrentChange = (page) => {
  currentPage.value = page;
};

const editProduct = (product) => {
  editForm.value = { ...product };
  dialogFormVisible.value = true;
};

const handleFileChange = (event) => {
  file.value = event.target.files[0];
};

const handleAdditionalFileChange = async (event) => {
  const newFile = event.target.files[0];
  if (newFile) {
    try {
      const formData = new FormData();
      formData.append('files', newFile); // 使用 'files' 作为参数名

      const response = await axios.post(`http://localhost:8080/api/images/${selectedProductId.value}`, formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      });

      // 处理上传成功的逻辑，例如更新界面或其他操作
      console.log('上传成功:', response.data);

      // 更新附加图片预览
      additionalFiles.value.push(newFile);
      additionalFilesPreview.value.push(URL.createObjectURL(newFile));

    } catch (error) {
      console.error('上传失败:', error);
    }

    // 清空文件输入框，以便可以连续添加相同文件
    event.target.value = '';
  }
};


const resetEditForm = () => {
  editForm.value = { id: '', name: '', quantity: '', price: '', ifground: 0, description: '', image: '' };
  file.value = null;
  additionalFiles.value = [];
  additionalFilesPreview.value = [];
  if (fileInput.value) {
    fileInput.value.value = null;
  }
};

const cancelEdit = () => {
  dialogFormVisible.value = false;
  resetEditForm();
};

const cancelAdditionalImageUpload = () => {
  additionalImageDialogVisible.value = false;
};


const deleteAdditionalImageUpload = async () => {
  try {
    // Assuming selectedProductId.value is set appropriately
    const response = await axios.delete(`http://localhost:8080/api/images/product/${selectedProductId.value}`);
    console.log('历史图片删除成功:', response.data);
    
    // 清空状态
    additionalImageDialogVisible.value = false;
    additionalFiles.value = [];
    additionalFilesPreview.value = [];
  } catch (error) {
    console.error('删除历史图片失败:', error);
  }
};



const updateProduct = async () => {
  const formData = new FormData();
  formData.append('name', editForm.value.name);
  formData.append('quantity', editForm.value.quantity);
  formData.append('price', editForm.value.price);
  formData.append('ifground', editForm.value.ifground ? 1 : 0);
  formData.append('description', editForm.value.description);
  if (file.value) {
    formData.append('image', file.value);
  }

  try {
    await axios.put(`http://localhost:8080/api/products/${editForm.value.id}`, formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      },
      params: { username: globalState.username } // 确保这里也传递了正确的 username 参数
    });
    await fetchData(); // 刷新表格数据
    dialogFormVisible.value = false;
    resetEditForm(); // 重置表单
  } catch (error) {
    console.error('Error updating product:', error);
  }
};;

const deleteProduct = async (id) => {
  try {
    await axios.delete(`http://localhost:8080/api/products/${id}`);
    fetchData();
  } catch (error) {
    console.error('Error deleting product:', error);
    alert("商品已被购买，不能彻底删除，可进行下架处理！！！")
  }
};

const openAdditionalImageDialog = (product) => {
  selectedProductId.value = product.id;
  additionalImageDialogVisible.value = true;
};

const uploadAdditionalImages = async () => {
  if (additionalFiles.value.length === 0) {
    alert('没有附加图片需要上传');
  }
  else{
    alert('所有图片上传成功');
    // 清空状态
    additionalFiles.value = [];
    additionalFilesPreview.value = [];
  }
  additionalImageDialogVisible.value = false;
};

onMounted(() => {
  fetchData();
});
</script>
<style scoped>
.dialog-footer {
  text-align: right;
}
.manage-form .manage-title {
    font-size: 2em;
    text-align: center;
    text-shadow: 5px 5px 5px #f719ad;
    color: #0f7a92;
  }
  
  .manage-form {
    background-color:rgb(223, 216, 225);
  }
</style>
